package com.lbx.redis;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

/**
 * @description:
 * @author: lbx
 * @create: 2018/7/19 14:23
 **/
@Component
public class RedisUtil {
    private static final Logger LOGGER    = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    @Getter
    private JedisCluster jedisCluster;

    /**
     * 设置缓存
     * @param key    缓存key
     * @param value  缓存value
     */
    public void set(String key, String value) {
        jedisCluster.set(key, value);
    }

    public String get(String key){
        return jedisCluster.get(key);
    }

    public byte[] get(byte[] key){
        return jedisCluster.get(key);
    }

    public void del(String key){
        jedisCluster.del(key);
    }

    public void del(String... keys){
        jedisCluster.del(keys);
    }

    /**
     * 设置缓存对象
     * @param key    缓存key
     * @param obj  缓存value
     */
    public <T> void setObject(String key, T obj , int expireTime) {
        jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));
    }

    /**
     * 获取指定key的缓存
     * @param key---JSON.parseObject(value, User.class);
     */
    public String getObject(String key) {
        return jedisCluster.get(key);
    }

    /**
     * 判断当前key值 是否存在
     *
     * @param key
     */
    public boolean hasKey(String key) {
        return jedisCluster.exists(key);
    }

    /**
     * 设置缓存，并且自己指定过期时间
     * @param key
     * @param value
     * @param expireTime 过期时间
     */
    public void setWithExpireTime( String key, String value, int expireTime) {
        jedisCluster.setex(key, expireTime, value);
    }


}
